//
//  JwCommon.m
//  JwPack
//
//  Created by 陈警卫 on 2024-08-13.
//

#import "JwCommon.h"
#import <CoreText/CoreText.h>

@implementation JwCommon

/// 判断(nil, NULL, [NSNull null]) 返回YES
+ (BOOL)isBlank:(id)value {
    if (!value) {
        return YES;
    }
    if ([value isEqual:[NSNull null]]) {
        return YES;
    }
    if ([value isKindOfClass:[NSNull class]]) {
        return YES;
    }
    return NO;
}

/// 时间戳
+ (NSString *)timestamp {
    return [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
}

/// 时钟戳
+ (NSString *)dateFmtString {
    NSDateFormatter *formatter  = [[NSDateFormatter alloc] init];
    formatter.dateFormat  = @"yyyyMMddHHmmssSSS";
    NSString *datefrom = [formatter stringFromDate:[NSDate date]];
    return datefrom;
}

/// 随机数
+ (NSString *)randomString {
    NSInteger random = arc4random() % 1000000000;
    return [NSString stringWithFormat:@"%06ld", (long)random];
}

/// 校验字符串
+ (NSString *)stringValue:(id)value {
    if ([value isKindOfClass:[NSNumber class]]) {
        value = ((NSNumber *)value).stringValue;
    }
    if ([value isKindOfClass:[NSString class]]) {
        return value;
    }
    return @"";
}

/// 退出程序
+ (void)exit {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [UIView animateWithDuration:0.5 animations:^{
        window.alpha = 0;
    } completion:^(BOOL finished) {
        exit(0);
    }];
}

/// 拉起拨打电话
- (void)openCallWithPhone:(NSString *)phone {
    NSString *cleanedString = [[phone componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789-+()"] invertedSet]] componentsJoinedByString:@""];
    NSString *escapedPhoneNumber = [cleanedString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSString *phoneURLString = [NSString stringWithFormat:@"tel://%@", escapedPhoneNumber];
    NSURL *phoneURL = [NSURL URLWithString:phoneURLString];
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([[UIApplication sharedApplication] canOpenURL:phoneURL]) {
            [[UIApplication sharedApplication] openURL:phoneURL options:@{} completionHandler:^(BOOL success) {
                
            }];
        }
    });
}


@end


@implementation JwCommon (JwUI)

/// 改变Label中的字体颜色
+ (void)label:(UILabel *)label text:(NSString *)text color:(UIColor *)color {
    NSArray *texts = @[text];
    NSArray *attrss = @[@{NSForegroundColorAttributeName: color}];
    [self label:label texts:texts attrss:attrss];
}

/// 改变Label中的字体大小
+ (void)label:(UILabel *)label text:(NSString *)text font:(UIFont *)font {
    NSArray *texts = @[text];
    NSArray *attrss = @[@{NSFontAttributeName: font}];
    [self label:label texts:texts attrss:attrss];
}

/// 改变Label中的字体属性
/// texts 需要改变的字符串数组
/// texts 对应的attrs属性
+ (void)label:(UILabel *)label texts:(NSArray *)texts attrss:(NSArray<NSDictionary<NSAttributedStringKey, id> *> *)attrss {
    if (!label || !texts || [texts count] != [attrss count]) {
        NSLog(@"[JwCommon] Invalid input parameters for (jw_label: texts: attrss:)");
        return;
    }
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];
    [texts enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *text = obj;
        NSUInteger index = idx;
        NSDictionary *attrs = attrss[index];
        NSRange range = NSMakeRange(0, [attStr length]);
        while (range.location != NSNotFound) {
            range = [[attStr string] rangeOfString:text options:NSLiteralSearch range:range];
            if (range.location != NSNotFound) {
                [attStr addAttributes:attrs range:range];
                range = NSMakeRange(range.location + range.length, [attStr length] - range.location - range.length);
            }
        }
    }];
    label.attributedText = attStr;
}

/// 获取字符串分页Range
/// content 字符串数据
/// font 字体
/// size 界面大小
/// return range数组
+ (NSArray *)pageRangesWithContent:(NSString *)content font:(UIFont *)font size:(CGSize)size {
    NSDate *date = [NSDate date];
    NSString *text = content;
    // 需要确定字体才能获取正确的range
    // ex. [UIFont fontWithName:@"Heiti SC" size:16];
    CGRect rect = CGRectMake(0, 0, size.width, size.height);

    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentLeft;
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attStr.length)];
    [attStr addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, attStr.length)];
    
    NSMutableArray *pageRanges = [NSMutableArray array];
    NSInteger rangeIndex = 0;
    for (NSInteger i = 0; i < NSIntegerMax; i++) {
        NSAttributedString *childStr = [attStr attributedSubstringFromRange:NSMakeRange(rangeIndex, attStr.length - rangeIndex)];
        CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)childStr);
        CGMutablePathRef path = CGPathCreateMutable();
        CGPathAddRect(path, NULL, rect);
        CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
        CFRange cfRange = CTFrameGetVisibleStringRange(frame);
        NSRange range = {rangeIndex, cfRange.length};
        [pageRanges addObject:[NSValue valueWithRange:range]];
        rangeIndex += range.length;
        CGPathRelease(path);
        CFRelease(frame);
        CFRelease(frameSetter);
        if (rangeIndex >= attStr.length) {
            break;
        }
    }
    NSTimeInterval second = [[NSDate date] timeIntervalSinceDate:date];
    NSLog(@"[JwCommon] pageRangesWithContent 耗时--%lf", second);
    return (NSArray *)pageRanges;
}

/// 固定角圆角
/// view 控件
/// corners 指定角
/// cornerRadius 圆角值
/// rect 控件坐标
+ (void)bezierRoundView:(UIView *)view corners:(UIRectCorner)corners cornerRadius:(NSInteger)cornerRadius rect:(CGRect)rect {
    [view.superview layoutIfNeeded];
    [view layoutIfNeeded];
    
    if (CGRectEqualToRect(rect, CGRectZero)) {
        rect = view.bounds;
    }
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = rect;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}


@end
